package zkapi;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * @program: hadoop
 * @description: zookeeper操作
 * @author: Qiang.Ye
 * @create: 2019-06-01 12:39
 **/
public class zkOperate {

    private     static      String      connnectString = "bigdata111:2181";
    private     static      int         sesstionTimeout = 2000;
    private     ZooKeeper    zkClient = null;


    @Before
    public  void init() throws IOException {

        zkClient = new ZooKeeper(connnectString, sesstionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
            //收到时间通知后的回调函数（用户的业务模式）
                System.out.println(event.getType()+"--"+event.getPath());
                try {
                    //再次启动监听
                    zkClient.getChildren("/",true);
                }catch (Exception e){

                }
            }
        });
    }


    @Test
    public void create() throws KeeperException, InterruptedException {
        //数据的增删改查
        //参数1：要创建的节点路径：参数2:节点数据 参数3：节点权限，参数4：节点的类型
        String nodeCreated = zkClient.create("/pangxie","aa".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }


    @Test
    public void get() throws KeeperException, InterruptedException {
        //数据的增删改查
        //参数1：要创建的节点路径：参数2:节点数据 参数3：节点权限，参数4：节点的类型
        List<String> childrens = zkClient.getChildren("/", true);
        childrens.forEach(e->{
            System.out.println(e);
        });
    }

    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat stat = zkClient.exists("/pangxie", false);
        System.out.println(stat == null ? "没有":"有");
    }

}
